package prjCode;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class AddIndex {

	private static Text empty = new Text();

	public static class MapClass extends Mapper<LongWritable, Text, Text, Text> {

		
		
		@Override
		public void map(LongWritable key, Text value, Context context) throws IOException,  InterruptedException {
			
			context.write(empty, value);		
		}

	}

	public static class ReduceClass extends Reducer<Text ,Text,IntWritable ,Text> {

		private IntWritable keyIndex = new IntWritable();
		private static int index = 0;

		@Override
		public void reduce(Text key, Iterable<Text> values, Context context) throws IOException,  InterruptedException {

			for(Text val : values)
			{
				index++;
				keyIndex.set(index);
				context.write(keyIndex ,val);
			}
			

		}
	}

	

	public static class PartitionerClass extends Partitioner<Text, Text> {
		// ensure that keys with same key are directed to the same reducer
		@Override
		public int getPartition(Text key,Text value, int numPartitions) {
			return  0;
		}
	}

	public static void main(String[] args) throws Exception {



		Configuration conf = new Configuration();
		Job job = new Job(conf, "Set index");
		job.setJarByClass(AddIndex.class);
		job.setMapperClass(AddIndex.MapClass.class);
		job.setReducerClass(AddIndex.ReduceClass.class);
		job.setOutputKeyClass(Iterable.class);
		job.setOutputValueClass(Text.class);
		job.setOutputValueClass(Text.class);
		job.setMapOutputKeyClass(Text.class);
		FileInputFormat.addInputPath(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, new Path(args[1]));
		System.exit(job.waitForCompletion(true) ? 0 : 1);
	}


}
